// Copyright 2022 a.o.smith ALL Rights Reserved
package com.liuxinlong.modules.project.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.liuxinlong.api.WeChatMessageInterface;
import com.liuxinlong.common.AosException;
import com.liuxinlong.common.ExcelData;
import com.liuxinlong.common.SnowFlake;
import com.liuxinlong.constant.ThreadLocalConstants;
import com.liuxinlong.constant.TimeFormatConstants;
import com.liuxinlong.enums.ProjectStatusEnum;
import com.liuxinlong.enums.FileBusinessTypeEnum;
import com.liuxinlong.enums.MatterSourceEnum;
import com.liuxinlong.enums.MessageContentTypeEnum;
import com.liuxinlong.enums.MessagePushBusinessEnum;
import com.liuxinlong.enums.ProjectDealEnum;
import com.liuxinlong.enums.ProjectLevelEnum;
import com.liuxinlong.enums.ProjectSourceEnum;
import com.liuxinlong.enums.ReturnCodes;
import com.liuxinlong.modules.dao.FileManageDao;
import com.liuxinlong.modules.dao.PatentDepartmentDao;
import com.liuxinlong.modules.dao.PatentProposalDao;
import com.liuxinlong.modules.dao.ProjectDao;
import com.liuxinlong.modules.dao.ProjectPatentExpandDao;
import com.liuxinlong.modules.dao.ProjectRelationDao;
import com.liuxinlong.modules.dao.RoleDao;
import com.liuxinlong.modules.dao.RoleRightDao;
import com.liuxinlong.modules.dao.UserDao;
import com.liuxinlong.modules.dao.UserMatterDao;
import com.liuxinlong.modules.dao.UserRoleRelationDao;
import com.liuxinlong.modules.entity.FileManage;
import com.liuxinlong.modules.entity.MessageConfiguration;
import com.liuxinlong.modules.entity.PatentDepartment;
import com.liuxinlong.modules.entity.Project;
import com.liuxinlong.modules.entity.ProjectPatentExpand;
import com.liuxinlong.modules.entity.ProjectRelation;
import com.liuxinlong.modules.entity.RoleRight;
import com.liuxinlong.modules.entity.User;
import com.liuxinlong.modules.entity.UserMatter;
import com.liuxinlong.modules.entity.UserRole;
import com.liuxinlong.modules.entity.UserRoleRelation;
import com.liuxinlong.modules.out.dto.ProjectDto;
import com.liuxinlong.modules.out.service.OutEcnService;
import com.liuxinlong.modules.out.service.OutPmpService;
import com.liuxinlong.modules.out.service.OutProjectService;
import com.liuxinlong.modules.project.controller.request.MergingProjectReq;
import com.liuxinlong.modules.project.service.ProjectService;
import com.liuxinlong.modules.system.service.FileManageService;
import com.liuxinlong.utils.ExcelUtils;
import com.liuxinlong.utils.IPUtils;
import com.liuxinlong.utils.ObjectUtils;
import com.liuxinlong.utils.PdfUtils;
import com.liuxinlong.utils.ThreadlocalUtils;
import com.liuxinlong.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 项目信息服务层实现类
 *
 * @author liuxinlong@hotwater.com.cn
 * @version 1.0.0
 * @since 2024年3月1日
 */
@Slf4j
@Service
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectDao projectDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private PatentDepartmentDao patentDepartmentDao;

    @Autowired
    private UserRoleRelationDao userRoleRelationDao;

    @Autowired
    private FileManageDao fileManageDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private FileManageService fileManageService;

    @Autowired
    private ProjectRelationDao projectRelationDao;

    @Autowired
    private PatentProposalDao patentProposalDao;

    @Autowired
    private OutProjectService outProjectService;

    @Autowired
    private ProjectPatentExpandDao projectPatentExpandDao;

    @Autowired
    private OutPmpService outPmpService;

    @Autowired
    private OutEcnService outEcnService;

    @Autowired
    private RoleRightDao roleRightDao;

    @Autowired
    private UserMatterDao userMatterDao;

    @Autowired
    private UserRoleRelationDao roleRelationDao;

    @Autowired
    private WeChatMessageInterface weChatMessageInterface;

    @Override
    public List<Map<String, Object>> pageProjectInfo(Map<String, Object> queryParam) {
        int startNum = (int) queryParam.get("startNum");
        List<Project> originList = projectDao.pageProjectList(queryParam);
        return completeResult(originList, startNum);
    }

    @Override
    public int getProjectCount(Map<String, Object> queryParam) {
        return projectDao.getProjectCount(queryParam);
    }

    @Override
    @Transactional
    public void addProjectInfo(Project project) {
//        Project oldInfo = projectDao.getProjectBySn(project.getProjectSn());
//        if (!ObjectUtils.isEmpty(oldInfo)) {
//            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "新增失败，项目已存在！");
//        }
        project.setId(SnowFlake.nextIdStr());
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (ObjectUtils.isEmpty(currentUser)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "当前用户不存在");
        }
        project.setDealStatus(ProjectDealEnum.PENDING.getValue());
        project.setProjectSource(1);
        String userId = currentUser.getId();
        project.setCreateUser(userId);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        project.setCreateTime(currentTime);
        projectDao.insert(project);
    }

    @Override
    @Transactional
    public void updateProjectInfo(Project project) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (ObjectUtils.isEmpty(currentUser)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户登陆状态异常！");
        }
        Project oldInfo = projectDao.selectById(project.getId());
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败，原项目信息不存在！");
        }
        project.setProjectSource(oldInfo.getProjectSource());
        project.setDealStatus(oldInfo.getDealStatus());
        project.setCreateTime(oldInfo.getCreateTime());
        project.setCreateUser(oldInfo.getCreateUser());
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        project.setUpdateTime(currentTime);
        project.setUpdateUser(currentUser.getId());
        projectDao.updateById(project);
    }

    @Override
    @Transactional
    public void deleteProjectInfo(String id) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (ObjectUtils.isEmpty(currentUser)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户登陆状态异常！");
        }
        Project project = projectDao.selectById(id);
        if (ObjectUtils.isEmpty(project)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "项目不存在！");
        }
        Map<String, Object> propParam = new HashMap<>();
        propParam.put("projectId", id);
        int proposalNum = patentProposalDao.getPatentProposalCount(propParam);
        if (proposalNum > 0) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "删除失败，项目存在关联风险专利！");
        }
        List<UserRoleRelation> userRoleRelationList = userRoleRelationDao.queryRelationByUserId(currentUser.getId());
        UserRole manageRole = roleDao.getRoleBySn("J017");
        List<UserRoleRelation> existList;
        if (ObjectUtils.isEmpty(manageRole)) {
            existList = new ArrayList<>();
            if (StringUtils.equals(currentUser.getId(), project.getCreateUser())) {
                UserRoleRelation userRoleRelation = new UserRoleRelation();
                userRoleRelation.setUserId(currentUser.getId());
                existList.add(userRoleRelation);
            }
        } else {
            existList = userRoleRelationList.stream().filter(relation -> StringUtils.equals(relation.getRoleId(), manageRole.getId())).collect(Collectors.toList());
        }
        if (existList.isEmpty()) {
            return;
        }
        project.setStatus(ProjectStatusEnum.REPEALED.getValue());
        project.setDealStatus(ProjectDealEnum.INVALID_DATA.getValue());
        project.setUpdateUser(currentUser.getId());
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        project.setUpdateTime(currentTime);
        projectDao.updateById(project);
    }

    @Override
    @Transactional
    public void mergingProjectInfo(MergingProjectReq req) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (ObjectUtils.isEmpty(currentUser)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户登陆状态异常！");
        }
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        List<String> parentList = req.getParentList();
        Map<Integer, Project> patentMap = new HashMap<>();
        int i = 1;
        List<Project> updateList = new ArrayList<>(parentList.size());
        List<ProjectRelation> relationList = new ArrayList<>(parentList.size());
        String id = SnowFlake.nextIdStr();
        int projectType = 1;
        for (String oldId : parentList) {
            Project oldProject = projectDao.selectById(oldId);
            if (ObjectUtils.isEmpty(oldProject)) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "原项目不存在！");
            }
            Map<String, Object> propParam = new HashMap<>();
            propParam.put("projectId", oldId);
            int proposalNum = patentProposalDao.getPatentProposalCount(propParam);
            if (proposalNum > 0) {
                throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "原项目存在关联风险专利！");
            }
            patentMap.put(i, oldProject);
            oldProject.setUpdateUser(currentUser.getId());
            oldProject.setUpdateTime(currentTime);
            oldProject.setDealStatus(ProjectDealEnum.INVALID_DATA.getValue());
            updateList.add(oldProject);
            projectType = projectType == oldProject.getProjectType() ? oldProject.getProjectType() : 2;
            ProjectRelation relation = new ProjectRelation();
            relation.setId(SnowFlake.nextIdStr());
            relation.setProjectId(id);
            relation.setRelationId(oldId);
            relation.setCreateUser(currentUser.getId());
            relation.setCreateTime(currentTime);
            relationList.add(relation);
            i++;
        }
        Project project = new Project();
        project.setProjectName(patentMap.get(req.getProjectName() > 0 ? req.getProjectName() : 1).getProjectName());
        project.setProjectSn(patentMap.get(req.getProjectSn() > 0 ? req.getProjectSn() : 1).getProjectSn());
        project.setProjectFinancialSn(patentMap.get(req.getProjectFinancialSn() > 0 ? req.getProjectFinancialSn() : 1).getProjectFinancialSn());
        project.setProjectLevel(patentMap.get(req.getProjectLevel() > 0 ? req.getProjectLevel() : 1).getProjectLevel());
        project.setStatus(patentMap.get(req.getStatus() > 0 ? req.getStatus() : 1).getStatus());
        project.setProjectManager(patentMap.get(req.getProjectManager() > 0 ? req.getProjectManager() : 1).getProjectManager());
        project.setDepartment(patentMap.get(req.getDepartment() > 0 ? req.getDepartment() : 1).getDepartment());
        project.setStartDate(patentMap.get(req.getStartDate() > 0 ? req.getStartDate() : 1).getStartDate());
        project.setEndDate(patentMap.get(req.getEndDate() > 0 ? req.getEndDate() : 1).getEndDate());
        project.setId(id);
        project.setDealStatus(ProjectDealEnum.VALID_DATA.getValue());
        project.setProjectSource(1);
        project.setProjectType(projectType);
        project.setCreateUser(currentUser.getId());
        project.setCreateTime(currentTime);
        projectDao.insert(project);
        if (!updateList.isEmpty()) {
            projectDao.updateBatchById(updateList);
        }
        if (!relationList.isEmpty()) {
            projectRelationDao.insertBatch(relationList);
        }
    }

    @Transactional
    @Override
    public void updateProjectDealStatus(String projectId, int targetStatus) {
        if (targetStatus > 3 || targetStatus < 1) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败，目标状态异常！");
        }
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (ObjectUtils.isEmpty(currentUser)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户登陆状态异常！");
        }
        Project oldInfo = projectDao.selectById(projectId);
        if (ObjectUtils.isEmpty(oldInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败，项目不存在！");
        }
        ProjectPatentExpand patentExpand = projectPatentExpandDao.selectById(projectId);
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        if (ObjectUtils.isEmpty(patentExpand)) {
            patentExpand = new ProjectPatentExpand();
            patentExpand.setId(projectId);
            patentExpand.setStage(1);
            patentExpand.setChildStage(1);
            patentExpand.setRiskStatus(0);
            patentExpand.setShowStatus(targetStatus == 2 ? 1 : 2);
            patentExpand.setMonitor(1);
            patentExpand.setCreateTime(currentTime);
            patentExpand.setCreateUser(currentUser.getId());
            projectPatentExpandDao.insert(patentExpand);
        } else {
            patentExpand.setShowStatus(targetStatus == 2 ? 1 : 2);
            patentExpand.setUpdateTime(currentTime);
            patentExpand.setUpdateUser(currentUser.getId());
            projectPatentExpandDao.updateById(patentExpand);
        }
        oldInfo.setDealStatus(targetStatus);
        oldInfo.setUpdateUser(currentUser.getId());
        oldInfo.setUpdateTime(currentTime);
        projectDao.updateById(oldInfo);
        if (targetStatus == 2) {
            String content = "风险管控系统新增项目 [ " + oldInfo.getProjectName() + " ] ，请项目经理及时更新设计差异点信息！";
            MessageConfiguration messageConfiguration = new MessageConfiguration();
            messageConfiguration.setBusinessType(MessagePushBusinessEnum.PATENT_RISK.getValue());
            messageConfiguration.setContent(content);
            messageConfiguration.setContentType(MessageContentTypeEnum.TEXT_CARD.getValue());
            List<String> targetList = new ArrayList<>();
            targetList.add(oldInfo.getProjectManager());
            PatentDepartment patentDepartment = patentDepartmentDao.selectById(oldInfo.getDepartment());
            if (!StringUtils.isEmpty(patentDepartment.getDutyUser())) {
                List<String> dutyUserList = Arrays.asList(patentDepartment.getDutyUser().split(","));
                targetList.addAll(dutyUserList);
            }
            weChatMessageInterface.pushMessage(targetList, null, messageConfiguration, currentTime);
        }
    }

    @Override
    public void exportProjectList(Map<String, Object> queryParam, HttpServletResponse response) {
        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        Map<String, Map<String, String>> departmentMap = patentDepartmentDao.getDepartmentMap();
        ExcelData data = new ExcelData();
        data.setFileName("项目信息清单导出excel.xlsx");
        List<Project> questionList = projectDao.pageProjectList(queryParam);
        String[] head = {"序号", "项目名称", "立项编号", "财务项目号", "项目经理", "项目等级", "项目状态", "项目类型", "责任部门", "处理状态", "项目来源", "开始日期", "截止日期", "完成日期"};
        data.setHead(head);
        String[][] dataList = new String[questionList.size()][head.length];
        int index = 0;
        for (Project item : questionList) {
            dataList[index][0] = String.valueOf(index + 1);
            dataList[index][1] = item.getProjectName();
            dataList[index][2] = item.getProjectSn();
            dataList[index][3] = item.getProjectFinancialSn();
            dataList[index][4] = userMap.containsKey(item.getProjectManager()) ? userMap.get(item.getProjectManager()).get("name") : "";
            dataList[index][5] = ProjectLevelEnum.getNameByValue(item.getProjectLevel());
            dataList[index][6] = ProjectStatusEnum.getNameByValue(item.getStatus());
            dataList[index][7] = item.getProjectType() == 1 ? "预研项目" : item.getProjectType() == 2 ? "新品开发" : item.getProjectType() == 3 ? "其他" : "未知类型";
            dataList[index][8] = departmentMap.containsKey(item.getDepartment()) ? departmentMap.get(item.getDepartment()).get("name") : "";
            dataList[index][9] = ProjectDealEnum.getNameByValue(item.getDealStatus());
            dataList[index][10] = item.getProjectSource() == 1 ? "RDKS" : item.getProjectSource() == 2 ? "PMP" : item.getProjectSource() == 3 ? "HTP" : "INFO";
            dataList[index][11] = item.getStartDate();
            dataList[index][12] = item.getEndDate();
            dataList[index][13] = item.getCloseDate();
            index++;
        }
        data.setData(Arrays.asList(dataList));
        ExcelUtils.exportExcel(response, data);
    }

    @Override
    public void exportProjectInfo(String id, HttpServletResponse response) {
        Project project = projectDao.selectById(id);
        if (ObjectUtils.isEmpty(project)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "导出失败，项目不存在！");
        }
        Map<String, Object> map = ObjectUtils.object2Map(project);
        // 项目经理
        User manager = userDao.selectById(project.getProjectManager());
        map.put("projectManagerName", manager.getName());
        // 责任部门
        PatentDepartment department = patentDepartmentDao.selectById(project.getDepartment());
        map.put("departmentName", department.getName());
        map.put("statusName", ProjectStatusEnum.getNameByValue(project.getStatus()));
        Map<String, Object> queryDifficultyParam = new HashMap<>();
        queryDifficultyParam.put("projectId", id);
//        queryDifficultyParam.put("pointType", 1);
        queryDifficultyParam.put("startNum", 0);
        queryDifficultyParam.put("pageSize", 10000);

        PdfUtils.generatePDFDoc("project.pdf", response, map, 1);
        String fileName = "test.pdf";
        String path = "pdf/";

//        try {
//            // 目标路径
//            File file = new File(path);
//            // 如果文件目录不存在，就执行创建
//            if (!file.isDirectory()) {
//                file.mkdirs();
//            }
//
//            //创建文档，设置页面大小、左右上下边距
//            Document document = new Document();
//
//            //处理中文显示问题，使用资源字体
//            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
//
//            Font dateTitle = new Font(bfChinese,7,Font.NORMAL);
//            Font title = new Font(bfChinese,12,Font.BOLD);//文字加粗
//            Font textFont = new Font(bfChinese,7,Font.NORMAL);//文字正常
//
//            //给出输出路径
//            PdfWriter.getInstance(document, new FileOutputStream(path+fileName));
//
//            //打开文档
//            document.open();
//
//            //标题
//            PdfPTable tableTitle = new PdfPTable(3);
//
//            PdfPTable codeTitle = new PdfPTable(1);
//            //生成一个7列的表格
//            PdfPTable table = new PdfPTable(7);
//
//            //定义每个单元格的宽度
//            float[] widthsHeaderTitle = {1f,1f,1f};
//            float[] widthsCodeTitle = {1f};
//            float[] widthsHeader = {1f,1f,1f,1f,1f,1f,2f};
//
//            float lineHeight = (float)20.0;
//
//            //设置表格每一格的宽度
//            tableTitle.setWidths(widthsHeaderTitle);
//            codeTitle.setWidths(widthsCodeTitle);
//            table.setWidths(widthsHeader);
//
//            //设置表格总体宽度
//            tableTitle.setWidthPercentage(100);
//            codeTitle.setWidthPercentage(100);
//            table.setWidthPercentage(100);
//
//            int colSpan = 1;
//
//            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            Date date = new Date(System.currentTimeMillis());
//            //添加标题
//            PdfUtils.createTableCellLeft("导出人：行如火", textFont, tableTitle, lineHeight, colSpan);
//            PdfUtils.createTableCellCenter("确认出差记录表", title, tableTitle, lineHeight, colSpan);
//            PdfUtils.createTableCellRight(formatter.format(date), dateTitle, tableTitle, lineHeight, colSpan);
//
//            document.add(tableTitle);
//            PdfUtils.createTableCellRight("功能码： XXXXXXXXX",textFont, codeTitle, lineHeight, colSpan);
//            document.add(codeTitle);
//            document.add(new Paragraph("\n"));
//
//            String[] array = {"报表生成日期 ","状态 ", "经办人员 ", "提交时间 ","复核人员 ", "复核时间 ", "情况补充 "};
//            for (String s : array) {
//                PdfUtils.createTableCell(s, textFont, table, lineHeight, colSpan);
//            }
//            List<Map<String, Object>> dataResult = PdfUtils.getResult();
//
//            for (Map<String, Object> map : dataResult) {
//                String dataTime = map.get("dateTime") != null?map.get("dateTime").toString():"0";
//                String status = "0";
//                if (null != map.get("status")) {
//                    if ("0".equals(map.get("status"))) {
//                        status = "待确认";
//                    }
//                    if ("1".equals(map.get("status"))) {
//                        status = "待复核";
//                    }
//                    if ("2".equals(map.get("status"))) {
//                        status = "已复核";
//                    }
//                }
//                String creator = map.get("creator") != null?map.get("creator").toString():"0";
//                String createTime = map.get("createTime") != null?map.get("createTime").toString():"0";
//                String updator = map.get("updator") != null?map.get("updator").toString():"0";
//                String updateTime = map.get("updateTime") != null?map.get("updateTime").toString():"0";
//                String description = map.get("description") != null?map.get("description").toString():"0";
//
//                PdfUtils.createTableCell(dataTime, textFont, table, lineHeight, colSpan);
//                PdfUtils.createTableCell(status, textFont, table, lineHeight, colSpan);
//                PdfUtils.createTableCell(creator, textFont, table, lineHeight, colSpan);
//                PdfUtils.createTableCell(createTime, textFont, table, lineHeight, colSpan);
//                PdfUtils.createTableCell(updator, textFont, table, lineHeight, colSpan);
//                PdfUtils.createTableCell(updateTime, textFont, table, lineHeight, colSpan);
//                PdfUtils.createTableCell(description, textFont, table, lineHeight, colSpan);
//            }
//            document.add(table);
//            document.close();
//
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        File targetFile = new File(fileName);

    }

    @Override
    public List<Map<String, Object>> queryMemberInfos(String id) {
        Project project = projectDao.selectById(id);
        if (ObjectUtils.isEmpty(project)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "项目信息不存在！");
        }
        List<Map<String, Object>> dataList = new ArrayList<>();
        List<String> allMemberList = new ArrayList<>();
        allMemberList.add(project.getProjectManager());

        Map<String, Map<String, String>> userMap = userDao.getUserPictureMap();
        String currentIp = IPUtils.getCurrentIp();
        for (String member : allMemberList) {
            if (userMap.containsKey(member)) {
                Map<String, String> data = userMap.get(member);
                Map<String, Object> memberMap = new HashMap<>();
                memberMap.put("id", data.get("id"));
                memberMap.put("name", data.get("name"));
                memberMap.put("image", data.containsKey("portrait") ? data.get("filePath").replace("upload", "http:\\\\" + currentIp + ":8090\\preview\\upload") : "");
                memberMap.put("memberType", StringUtils.equals(member, project.getProjectManager()) ? 1 : 2);
                dataList.add(memberMap);
            }
        }
        return dataList;
    }

    @Override
    public Map<String, Object> queryProjectSummary() {
        Map<String, Object> queryParam = new HashMap<>();
        return projectDao.queryProjectSummary(queryParam);
    }

    @Override
    public Map<String, Object> queryProjectDetail(String id) {
        Map<String, Object> detailMap = new HashMap<>();

        // 项目信息
        Project project = projectDao.selectById(id);
        if (ObjectUtils.isEmpty(project)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "项目不存在！");
        }

        // 文件信息
        Map<String, Object> queryFileParam = new HashMap<>();
        queryFileParam.put("businessId", id);
        queryFileParam.put("businessType", FileBusinessTypeEnum.PROJECT_FILE.getValue());
        int fileCount = fileManageDao.getFileManageCount(queryFileParam);
        detailMap.put("fileNum", fileCount);

        // 剩余时间
        String leftDay;
        if (project.getStatus() == ProjectStatusEnum.FINISHED.getValue() || project.getStatus() == ProjectStatusEnum.REPEALED.getValue()) {
            leftDay = ProjectStatusEnum.getNameByValue(project.getStatus());
        } else {
            Date deadline = TimeUtils.formatTime(project.getEndDate(), TimeFormatConstants.YYYY_MM_DD);
            leftDay = TimeUtils.fromDeadlineDays(deadline);
        }
        detailMap.put("leftDay", leftDay);
        return detailMap;
    }

    @Override
    public void updateProjectMemberInfo(String projectId, String memberId, int operateType) {
        Project projectInfo = projectDao.selectById(projectId);
        if (ObjectUtils.isEmpty(projectInfo)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "修改失败，项目不存在！");
        }

        projectDao.updateById(projectInfo);
    }

    @Override
    public void addFileInfos(MultipartRequest multipartRequest) {
        String projectId = ((StandardMultipartHttpServletRequest) multipartRequest).getParameterMap().get("projectId")[0];
        List<Map<String, Object>> dataList = fileManageService.batchUploadFileLocal(multipartRequest, FileBusinessTypeEnum.PROJECT_FILE.getValue());
        if (ObjectUtils.isEmpty(dataList)) {
            return;
        }
        String[] fileList = dataList.stream().map(map -> (String) map.get("id")).collect(Collectors.toList()).toArray(new String[0]);
        fileManageDao.batchUpdateBusinessFile(fileList, projectId);
    }

    @Override
    public void downloadProjectFile(String id, HttpServletResponse response) {
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        if (ObjectUtils.isEmpty(currentUser)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "用户无权限！");
        }
        FileManage fileManage = fileManageDao.selectById(id);
        if (ObjectUtils.isEmpty(fileManage)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "文件不存在！");
        }
        Project project = projectDao.selectById(fileManage.getBusinessId());
        if (ObjectUtils.isEmpty(project)) {
            throw new AosException(ReturnCodes.HTTP_PARAM_ERROR, "项目不存在！");
        }
        List<String> allUserList = new ArrayList<>();
        allUserList.add(project.getProjectManager());
        if (allUserList.contains(currentUser.getId())) {

        }
    }

    @Override
    public void syncProjectInfo(Map<String, Object> queryParam, int auto, String source) {
        String currentTime = TimeUtils.getDate(TimeFormatConstants.YYYY_MM_DD_HH_MM_SS);
        User currentUser = auto == 1 ? null : (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        List<ProjectDto> incrementalProjectList = new ArrayList<>();
        if (StringUtils.isEmpty(source) || source.contains("3")) {
            List<ProjectDto> htpProjectList = outProjectService.queryUpdateProjectList(queryParam);
            incrementalProjectList.addAll(htpProjectList);
        }
        if (StringUtils.isEmpty(source) || source.contains("4")) {
            List<ProjectDto> infoProjectList = outEcnService.queryUpdateProjectList(queryParam);
            incrementalProjectList.addAll(infoProjectList);
        }
        if (StringUtils.isEmpty(source) || source.contains("2")) {
            List<ProjectDto> pmpProjectList = outPmpService.queryUpdateProjectList(queryParam);
            incrementalProjectList.addAll(pmpProjectList);
        }
        if (incrementalProjectList.size() == 0) {
            log.info("项目信息无需更新！");
            return;
        }
        // 用户列表
        List<User> userList = userDao.getUserBaseList();
        Map<String, User> userNameMap = new HashMap<>(userList.size());
        Map<String, User> userMailMap = new HashMap<>(userList.size());
        for (User u : userList) {
//            if (userMailMap.containsKey(u.getEmail())) {
//                continue;
//            }
//            userMailMap.put(u.getEmail(), u);
            if (userNameMap.containsKey(u.getName())) {
                continue;
            }
            userNameMap.put(u.getName(), u);
        }

        // 项目列表
        Map<String, String> departmentMap = patentDepartmentDao.getDepartmentBranchMap();
        List<Project> projectList = new ArrayList<>(incrementalProjectList.size());
        for (ProjectDto dto : incrementalProjectList) {
            Project project = new Project();
            project.setId(SnowFlake.nextIdStr());
            project.setProjectSource(dto.getProjectSource());
            project.setDealStatus(ProjectDealEnum.PENDING.getValue());
            project.setCreateTime(currentTime);
            project.setCreateUser(!ObjectUtils.isEmpty(currentUser) ? currentUser.getId() : "系统");
            if (StringUtils.isEmpty(dto.getProjectManager())) {
                project.setProjectManager("");
            } else {
                if (!userNameMap.containsKey(dto.getProjectManager().trim())) {
                    project.setProjectManager(dto.getProjectManager());
                } else {
                    User manageUser = userNameMap.get(dto.getProjectManager().trim());
                    project.setProjectManager(manageUser.getId());
                    project.setDepartment(departmentMap.get(manageUser.getDepartment()));
                }
            }
            if (StringUtils.isEmpty(dto.getDirectorContact())) {
                project.setProjectDirector(dto.getProjectDirector());
            } else {
                if (!userNameMap.containsKey(dto.getDirectorContact().trim())) {
                    project.setProjectDirector(dto.getDirectorContact());
                } else {
                    project.setProjectDirector(userMailMap.get(dto.getDirectorContact().trim()).getId());
                }
            }
            project.setProjectSn(dto.getProjectSn());
            project.setProjectFinancialSn(dto.getProjectFinancialSn());
            project.setProjectName(dto.getProjectName());
            project.setProjectLevel(ProjectLevelEnum.getValueByName(dto.getProjectLevel().trim()));
            project.setStartDate(dto.getStartDate());
            project.setEndDate(dto.getEndDate());
            projectList.add(project);
        }
        if (!ObjectUtils.isEmpty(projectList)) {
            projectDao.insertBatch(projectList);
            UserMatter userMatter = new UserMatter();
            userMatter.setId(SnowFlake.nextIdStr());
            userMatter.setCreateTime(currentTime);
            userMatter.setContent("存在未处理项目更新信息，请及时处理！");
            userMatter.setSourceType(MatterSourceEnum.PROJECT_MANAGE.getValue());
            userMatter.setSourceId(projectList.get(0).getId());
            List<RoleRight> roleRightList = roleRightDao.queryRoleByMenu("240108");
            userMatter.setPendingRole(roleRightList.get(0).getRole());
            userMatterDao.insert(userMatter);
            List<String> msgUserList = roleRelationDao.getUserByRoles(roleRightList.stream().map(RoleRight::getRole).collect(Collectors.toList()));
            MessageConfiguration messageConfiguration = new MessageConfiguration();
            messageConfiguration.setBusinessType(MessagePushBusinessEnum.OTHER.getValue());
            messageConfiguration.setContent(userMatter.getContent());
            messageConfiguration.setContentType(MessageContentTypeEnum.TEXT_CARD.getValue());
            weChatMessageInterface.pushMessage(msgUserList, null, messageConfiguration, currentTime);
        }

        log.info("SyncProjectInfoTask end...sync {} project records", projectList.size());
    }

    /**
     * 补全数据
     *
     * @param originList 原始数据
     * @param startNum   起始数
     * @return 补全数据列表
     */
    private List<Map<String, Object>> completeResult(List<Project> originList, int startNum) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        if (ObjectUtil.isEmpty(originList)) {
            return resultList;
        }
        User currentUser = (User) ThreadlocalUtils.getCache(ThreadLocalConstants.USER_INFO);
        String userId = currentUser.getId();
        List<UserRoleRelation> userRoleRelationList = userRoleRelationDao.queryRelationByUserId(userId);
        UserRole manageRole = roleDao.getRoleBySn("J017");
        List<UserRoleRelation> existList;
        if (ObjectUtils.isEmpty(manageRole)) {
            existList = new ArrayList<>();
        } else {
            existList = userRoleRelationList.stream().filter(relation -> StringUtils.equals(relation.getRoleId(), manageRole.getId())).collect(Collectors.toList());
        }
        boolean defaultPermission = !existList.isEmpty();

        UserRole highRole = roleDao.getRoleBySn("J016");
        List<UserRoleRelation> existHighList;
        if (ObjectUtils.isEmpty(highRole)) {
            existHighList = new ArrayList<>();
        } else {
            existHighList = userRoleRelationList.stream().filter(relation -> StringUtils.equals(relation.getRoleId(), highRole.getId())).collect(Collectors.toList());
        }

        Map<String, Map<String, String>> userMap = userDao.getUserMap();
        Map<String, Map<String, String>> departmentMap = patentDepartmentDao.getDepartmentMap();
        int sort = startNum + 1;
        for (Project item : originList) {
            Map<String, Object> map = ObjectUtils.object2Map(item);
            map.put("sort", sort);
            map.put("statusName", ProjectStatusEnum.getNameByValue(item.getStatus()));
            map.put("dealStatusName", ProjectDealEnum.getNameByValue(item.getDealStatus()));
            if (userMap.containsKey(item.getProjectManager())) {
                Map<String, String> projectManagerMap = userMap.get(item.getProjectManager());
                map.put("projectManagerName", projectManagerMap.get("name"));
                map.put("projectManagerContact", projectManagerMap.get("email"));
            } else {
                map.put("projectManagerName", "");
                map.put("projectManagerContact", "");
            }
            map.put("projectLevelName", ProjectLevelEnum.getNameByValue(item.getProjectLevel()));
            map.put("createUserName", userMap.containsKey(item.getCreateUser()) ? userMap.get(item.getCreateUser()).get("name") : item.getCreateUser());
            map.put("projectSourceName", ProjectSourceEnum.getNameByValue(item.getProjectSource()));
            map.put("projectTypeName", item.getProjectType() == 1 ? "预研项目" : item.getProjectType() == 2 ? "新品开发" : item.getProjectType() == 3 ? "其他" : "未知类型");
            map.put("departmentName", departmentMap.containsKey(item.getDepartment()) ? departmentMap.get(item.getDepartment()).get("name") : "");
            boolean highPermission = !existHighList.isEmpty();
            map.put("checkPermission", defaultPermission || highPermission || item.getStatus() == ProjectStatusEnum.FINISHED.getValue());
            map.put("modifyPermission", defaultPermission || StringUtils.equals(item.getProjectManager(), userId));
            map.put("expertPermission", defaultPermission);
            map.put("highPermission", highPermission);
            resultList.add(map);
            sort++;
        }
        return resultList;
    }
}
